﻿using System;
using NOSDC.Pocos;
using NOSDC.Repositories.Users;

namespace NOSDC.Services
{
    public sealed class AccountService : IAccountService
    {
        private readonly IAccountRepository _repository;

        public AccountService()
        {
            _repository = new AccountRepository();
        }

        public string GenerateRecoveryLink(Guid token)
        {
            return String.Format("http://www.nosdc.net/Account/RecoverPassword?token={0}", token);
        }

        public PasswordRecovery CreateRecoveryRequest(PasswordRecovery request)
        {
            request.Expiry = DateTime.Now.AddDays(1);
            request.RecoveryToken = Guid.NewGuid();
            request.LinkGenerated = GenerateRecoveryLink(request.RecoveryToken);
            request.DateRecovered = null;

            _repository.AddPasswordRecoveryRequest(request);

            return request;
        }

        public void UserHasRecovered(Guid token)
        {
            _repository.HasRecoveredPassword(token, DateTime.Now);
        }

        public string RecoveryRequestEmail(Guid token)
        {
            return _repository.HasValidPasswordRecoveryRequest(token).Email;
        }

        public bool ValidateRecovery(Guid token, DateTime date)
        {
            var request = _repository.HasValidPasswordRecoveryRequest(token);

            if (request == null || token != request.RecoveryToken) return false;
            return request.Expiry >= date && !request.HasRecovered;
        }

    }
}
